import javax.imageio.stream.ImageInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoServer {
    ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        this.serverSocket = new ServerSocket(port);
    }
   public void start() throws IOException {
       System.out.println("服务器启动");
        while(true){
            Socket clientSocket = serverSocket.accept();
            processConnection(clientSocket);
        }
   }

    private void processConnection(Socket clientSocket) {
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
while(true){
    Scanner scanner = new Scanner(inputStream);
    if (!scanner.hasNext()){
        break;
    }
    String request = scanner.next();
    String respond = process(request);
    PrintStream printStream = new PrintStream(outputStream);
    printStream.println(respond);
    printStream.flush();//这里要加这个,不然如果只有一个请求,不会马上执行,就需要多个请求才会执行.如果加了flush,就可以马上执行;(至于为什么一个不执行:是因为效率)
    System.out.printf("[%s:%d] req: %s, resp: %s\n", clientSocket.getInetAddress(),respond);
}
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9000);
        tcpEchoServer.start();
        
    }
}
